import logging
from typing import Any

from aiogram import Bot, types
from aiogram_dialog import DialogManager, StartMode
from fluentogram import TranslatorRunner

from src.bot.services.tg_helpers import answer_msg_with_autodelete, send_tg_message
from src.bot.states import ClientSG
from src.config import Settings
from src.database.services.order import OrderService
from src.database.services.product import ProductService
from src.database.services.statistics import StatsService
from src.database.services.user import UserService

logger = logging.getLogger(__name__)


async def set_category_id(
    _,
    __,
    manager: DialogManager,
    category_id: str,
):
    manager.dialog_data["category_id"] = int(category_id)
    await manager.next()


async def set_country_id(
    _,
    __,
    manager: DialogManager,
    country_id: str,
):
    manager.dialog_data["country_id"] = int(country_id)
    await manager.next()


async def set_amount(
    message: types.Message | types.CallbackQuery,
    widget: Any,
    manager: DialogManager,
    amount: int | None = None,
):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    available_count = manager.dialog_data["products_count"]

    if not amount:
        try:
            amount = int(widget.widget_id)
        except ValueError:
            pass

    if amount and amount > available_count:
        error_msg = locale.get("amount-gt-than-available")
        if isinstance(message, types.Message):
            await message.delete()
            await answer_msg_with_autodelete(message, error_msg)
        else:
            await message.answer(error_msg)
        return

    manager.dialog_data["selected_amount"] = amount if amount else widget.widget_id

    await manager.next()


async def create_order(
    call: types.CallbackQuery,
    _,
    manager: DialogManager,
):
    """Создаем заказ"""

    bot: Bot = manager.middleware_data.get("bot")
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    config: Settings = manager.middleware_data.get("config")
    order_service: OrderService = manager.middleware_data.get("order_service")
    product_service: ProductService = manager.middleware_data.get("product_service")
    user_service: UserService = manager.middleware_data.get("user_service")
    stats_service: StatsService = manager.middleware_data.get("stats_service")

    order_summ: float = manager.dialog_data.get("order_summ")
    discount_summ: float = manager.dialog_data.get("discount_summ", 0)
    promocode_id: int = manager.dialog_data.get("promocode_id")

    user = await user_service.get_user_by_telegram_id(call.from_user.id)

    if user.balance < order_summ:
        await call.answer(locale.get("not-enough-balance", balance=user.balance))
        return

    products = await product_service.get_available_products(
        manager.dialog_data.get("category_id"),
        manager.dialog_data.get("selected_amount"),
    )

    order = await order_service.create_order(
        user_tg_id=call.from_user.id,
        order_sum=order_summ,
        products=products,
        promocode_id=promocode_id,
    )
    manager.dialog_data["order_id"] = order.id
    await stats_service.add_stats(orders_created=1)
    await stats_service.add_stats(products_purchased=len(products))

    await send_tg_message(
        bot,
        config.tg_bot.admin_channel_id,
        locale.get(
            "new-order-notification",
            order_id=order.id,
            summ=order.summ,
            discount_summ=discount_summ,
        ),
    )

    await call.answer(locale.get("order-created-msg"))

    await manager.next()
